package com.fly.controller;

import com.fly.bean.*;
import com.fly.service.PermissionService;
import com.fly.util.JWTUtil;
import com.fly.util.Msg;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.nio.cs.ext.MS874;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/permission")
public class PermissionController {

    @Resource
    private PermissionService permissionService;

    /**
     * 根据得到的token判断用户登录的角色是什么，其有一些什么样的权限
     * @param request
     * @return
     */
    @RequestMapping("/getResources")
    @ResponseBody
    public Msg getAllResourcesByResourcesId(HttpServletRequest request){
        //开始用户认证
        String token = request.getHeader("Authorization");
        //解密得到token信息
        Users user = JWTUtil.unsign(token,Users.class);
        //得到用户ID信息
        Integer userId = user.getUserId();
//        System.out.println("userId = " + userId);
        //通过用户Id得到角色Id信息
        Integer roleId = permissionService.selectRoleIdByUserId(userId);
        //通过角色Id得到资源Id信息
        Integer[] resoursesIds = permissionService.selectResourcesIdByRoleId(roleId);
        //创建List集合存储资源对象
        List<Resources> resourceList = new ArrayList<>();
        //循环得到所有的资源信息通过所有的资源Id
        for (int i = 0;i<resoursesIds.length;i++){
            Resources resources = permissionService.selectResourcesByResourcesId(resoursesIds[i]);

            //资源集合添加资源对象
            resourceList.add(resources);
        }

        if (resourceList != null){
            return  Msg.success().add("resourceList",resourceList);
        }else{
            return Msg.fail();
        }
    }

    /**
     * 根据角色名称查询它所对应的权限资源信息
     * @param roleName
     * @return
     */
    @RequestMapping("/getResourcesByRoleName")
    @ResponseBody
    public Msg getAllResourcesByRoleName(String roleName){
        //根据角色名称得到角色Id
        Integer roleId = permissionService.selectRoleIdByRoleName(roleName);
        //通过角色Id得到资源Id信息
        Integer[] resourcesIds = permissionService.selectResourcesIdByRoleId(roleId);
        //创建List集合存储资源对象
        List<Resources> resourceList = new ArrayList<Resources>();
        //循环得到所有的资源信息通过所有的资源Id
        for (int i = 0;i<resourcesIds.length;i++){
            Resources resources = permissionService.selectResourcesByResourcesId(resourcesIds[i]);
            System.out.println();
            //资源集合添加资源对象
            resourceList.add(resources);
        }

        if (resourceList != null){
            //成功返回数据
            return Msg.success().add("resourceList",resourceList);
        }else{
            return Msg.fail();
        }
    }

    /**
     * 添加角色信息
     * @param parentName
     * @param functionName
     * @param functionURL
     * @param sysProValueName
     * @return
     */
    @RequestMapping("/addResources")
    @ResponseBody
    public Msg addResources(String parentName,String functionName,String functionURL,String sysProValueName){
        //根据父节点名称得到资源类型ResourcesType
        Integer resourcesType = permissionService.selectResourcesTypeResourcesName(parentName);
        //子节点的资源类型为父节点的资源类型+1(下一级)
        resourcesType = resourcesType + 1;
        //根据父节点名称得到ResourcesId
        Integer resourcesId = permissionService.selectResourcesIdByResourcesName(parentName);
        //通过父节点的resourcesId得到其子节点的数量
        Integer number = permissionService.selectCountByResourcesId(resourcesId);
        //通过其父节点的子节点数量得到其排行老几(显示顺序)
        Integer priority = number + 1;
        //查询资源状态信息根据sysProValueName
        Integer resourcesState = permissionService.selectResourcesStateBySysProValueName(sysProValueName);
        //创建SystemPropertiesValue对象
        SystemPropertiesValue systemPropertiesValue = new SystemPropertiesValue();
        systemPropertiesValue.setId(resourcesState);

        //创建资源对象
        Resources resources = new Resources();
        resources.setResourcesName(functionName);
        resources.setResourcesType(resourcesType);
        resources.setPriority(priority);
        resources.setParentId(resourcesId);
        resources.setPermission(functionURL);
        resources.setSystemPropertiesValue(systemPropertiesValue);

        //添加资源信息
        Integer result = permissionService.addResources(resources);

        if (result > 0){
            return Msg.success();
        }else {
            return Msg.fail();
        }
    }

    /**
     * 根据角色Id和资源Id添加role_resources_relation数据
     * @param resourcesNames
     * @param roleName
     * @return
     */
    @RequestMapping("/addRole_resources_relation")
    @ResponseBody
    public Msg addRole_resources_relation(String[] resourcesNames,String roleName){
        //根据资源名称循环得到资源Id
        Integer[] resourcesIds = new Integer[resourcesNames.length];
        for (int i = 0;i<resourcesNames.length;i++){
            resourcesIds[i] = permissionService.selectResourcesIdByResourcesName2(resourcesNames[i]);
        }
        //根据角色名称查询角色Id
        Integer roleId = permissionService.selectRoleIdByRoleName(roleName);

        //根据角色ID得到资源id信息
        Integer[] resourcesId = permissionService.selectResourcesIdByRoleId(roleId);

        //标识
        boolean result = false;

        //如果还有数据就要先删除，如果没有数据就不用删除
        if (resourcesId.length != 0){
            if(resourcesIds != null){
                //如果资源Id数组不为空，就说明配置了权限信息，如果我空就视为瞎搞，不允许，一个角色必须要有相应的权限
                //先删除还角色已有的权限
                Integer deleteResult = permissionService.deleteRoleAndResourcesByRoleId(roleId);

                //删除成功后再为该角色添加相应的权限信息
                if (deleteResult > 0){
                    //创建资源角色关系对象
                    RoleReRela roleReRela = new RoleReRela();
                    //创建角色对象
                    Role role = new Role();
                    role.setRoleId(roleId);
                    roleReRela.setRole(role);
                    //循环添加数据
                    for (int i = 0;i<resourcesIds.length;i++){
                        //循环创建资源对象
                        Resources resources = new Resources();
                        resources.setResourcesId(resourcesIds[i]);
                        roleReRela.setResources(resources);
                        //添加角色资源关系数据
                        Integer addResult = permissionService.addRole_resources_relation(roleReRela);
                        if (addResult > 0){
                            result = true;
                        }
                    }
                }
            }
        }else{
            //创建资源角色关系对象
            RoleReRela roleReRela = new RoleReRela();
            //创建角色对象
            Role role = new Role();
            role.setRoleId(roleId);
            roleReRela.setRole(role);
            //循环添加数据
            for (int i = 0;i<resourcesIds.length;i++){
                //循环创建资源对象
                Resources resources = new Resources();
                resources.setResourcesId(resourcesIds[i]);
                roleReRela.setResources(resources);
                //添加角色资源关系数据
                Integer addResult = permissionService.addRole_resources_relation(roleReRela);
                if (addResult > 0){
                    result = true;
                }
            }
        }
        if (result){
            return Msg.success();
        }else {
            return Msg.fail();
        }
    }

    /**
     * 得到所有的角色名称
     * @return
     */
    @RequestMapping("/getAllRoleName")
    @ResponseBody
    public Msg getAllRoleName(){
        String[] roleNames = permissionService.selectAllRoleName();

        if (roleNames != null){
            return Msg.success().add("roleNames",roleNames);
        }else{
            return Msg.fail();
        }
    }


}
